//
//  String+Extension.swift
//  PMS
//
//  Created by 何海涛 on 15/10/16.
//  Copyright © 2015年 途家. All rights reserved.
//

import Foundation

extension String {
    
    
    public func reverseStr() -> String {
        
        let str = self as NSString
        let length = self.length
        let reverseString = NSMutableString()
        for i in 0..<length {
            let c = str.character(at: length-i-1)
            reverseString.appendFormat("%c", c)
        }
        return (reverseString as String).uppercased()
        
    }
    
//    public func MD5ResultUppercaseString() -> String {
//        return self.md5.uppercased()
//    }
    
    public func getRectSizeOfFont(_ font: UIFont, constraintSize: CGSize)-> CGSize {
        let attributes = [NSAttributedString.Key.font:font]
        let option = NSStringDrawingOptions(rawValue:NSStringDrawingOptions.usesLineFragmentOrigin.rawValue | NSStringDrawingOptions.usesFontLeading.rawValue)
        let size = self.boundingRect(with: constraintSize, options: option, attributes: attributes, context: nil).size
        return size
    }
    
    public static func getTextRectSize(_ text:String,font:UIFont,size:CGSize) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let strSize:CGSize = text.boundingRect(with: size, options: option, attributes: attributes, context: nil).size
        return strSize;
    }
    public static func getTextSize(_ text:String,font:CGFloat, constraintSize: CGSize) -> CGSize {
        
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: font)]
        //        let option = NSStringDrawingOptions(rawValue:NSStringDrawingOptions.usesLineFragmentOrigin.rawValue | NSStringDrawingOptions.usesFontLeading.rawValue)
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let strSize:CGSize = text.boundingRect(with: constraintSize, options: option, attributes: attributes, context: nil).size
        return strSize;
        
    }
    
    public func  charAt(_ Index:Int)-> unichar{
        return (self as NSString).character(at: Index)
    }
    
    public static func limitTheStringLength(_ tranString : String,maxCharacters:Int)->String{
        
        /** 限制字符串的位数 多余的中间用 ...代替。 */
        if tranString.length>maxCharacters{
            let str = (tranString as NSString).substring(to: maxCharacters/2)+"..."+(tranString as NSString).substring(from: tranString.length-maxCharacters/2)
            return str
        }else{
            return tranString
        }
    }
    
    //计算字节数 一个中文2个字节
    public func getStringByte() -> Int {
        var length = 0
        for char in self {
            length += "\(char)".lengthOfBytes(using: String.Encoding.utf8) == 3 ? 2 : 1
        }
        return length
    }
}

extension String {
    
    public func toDate() -> Date? {
        return self.toDate("yyyy.MM.dd") ?? self.toDate("yyyy-MM-dd") ?? self.toDate("yyyy/MM/dd") ?? self.toDate("yyyy.M.d") ?? self.toDate("yyyy-M-d") ?? self.toDate("yyyy/M/d")
    }
    
    public func toDate(_ format : String) -> Date? {
        let formatter = TujiaDateFormatter.standard
        formatter.dateFormat = format
        return formatter.date(from: self)
    }
    
    public func toDateTime(_ dateFormat : String = "yyyy.MM.dd", afterDate : String = " HH:mm:ss") -> Date? {
        let formatter = TujiaDateFormatter.standard
        formatter.dateFormat = dateFormat + afterDate
        return formatter.date(from: self)
    }
    
    public func trim() -> String {
        return self.trimmingCharacters(in: CharacterSet(charactersIn: " "))
    }
    
    public var length : Int { return self.count }
    
    public func sizeWithAttributes(_ attrs : [NSAttributedString.Key : AnyObject]?) -> CGSize {
        return (self as NSString).size(withAttributes: attrs)
    }
    
    /** 针对的是宽度不受限制的字符串。 */
    public func stringWidth(_ font:CGFloat) -> CGFloat {
        return String.getTextSize(self, font: font, constraintSize:  CGSize(width:CommonDefine.kScreenWidth, height: CommonDefine.kScreenWorkHeight)).width
    }
    
    public func replaceMiddle(leftKeep left: Int, rightKeep right: Int, replaceCharacter : Character = "*") -> String {
        var copy = String(self)
        if self.length <= (left + right) { return copy }
        let delta = self.length - left - right
        let replaceVal = String(repeating: String(replaceCharacter), count: delta)
        copy.replaceSubrange(self.index(self.startIndex, offsetBy: left)..<self.index(self.startIndex, offsetBy: left+delta), with: replaceVal)
        return copy
    }
    
    /// 用于处理格式化字符串。例如输入"aa%sbbb"，返回(["aa", "bbb"], ["%s"])
    public func splitByPercentX() -> ([String], [String]) {
        var input = self
        var output1: [String] = []
        var output2: [String] = []
        while input.count > 0 {
            if let match = input.range(of: "([^%]|^)(%%)*%(\\d\\$)?[A-Za-z@]", options: .regularExpression) {
//                let sub = input.substring(to: match.upperBound)
//                let indexOffset = sub.substring(from: sub.characters.index(sub.endIndex, offsetBy: (-2))).characters.first == "%" ? -2 : -4
//                let index = sub.characters.index(sub.endIndex, offsetBy: indexOffset)
//                output1.append(sub.substring(to: index))
//                output2.append(sub.substring(from: index))
//                input = input.substring(from: match.upperBound)
                let sub = input[..<match.upperBound]
                let startIndex = sub.index(sub.endIndex, offsetBy: (-2))
                let indexOffset = sub[startIndex...].first == "%" ? -2 : -4
                let index = sub.index(sub.endIndex, offsetBy: indexOffset)
                output1.append(String(sub[..<index]))
                output2.append(String(sub[index...]))
                input = String(input[match.upperBound...])
            } else {
                output1.append(input)
                input = ""
            }
        }
        return (output1, output2)
    }
    
    /// 用于处理格式化字符串。例如输入"aa%sbbb"，返回(["aa", "%s", "bbb"], ["%s"])
    public func splitFullByPercentX() -> ([String], [String]) {
        var input = self
        var output1: [String] = []
        var output2: [String] = []
        while input.count > 0 {
            if let match = input.range(of: "([^%]|^)(%%)*%(\\d\\$)?[A-Za-z@]", options: .regularExpression) {
//                let sub = input.substring(to: match.upperBound)
//                let indexOffset = sub.substring(from: sub.characters.index(sub.endIndex, offsetBy: (-2))).characters.first == "%" ? -2 : -4
//                let index = sub.characters.index(sub.endIndex, offsetBy: indexOffset)
//                output1.append(sub.substring(to: index))
//                let percentStr = sub.substring(from: index)
//                output1.append(percentStr)
//                output2.append(percentStr)
//                input = input.substring(from: match.upperBound)
                let sub = input[..<match.upperBound]
                let startIndex = sub.index(sub.endIndex, offsetBy: (-2))
                let indexOffset = sub[startIndex...].first == "%" ? -2 : -4
                let index = sub.index(sub.endIndex, offsetBy: indexOffset)
                output1.append(String(sub[..<index]))
                let percentStr = String(sub[index...])
                output1.append(percentStr)
                output2.append(percentStr)
                input = String(input[match.upperBound...])
            } else {
                output1.append(input)
                input = ""
            }
        }
        return (output1, output2)
    }
    
    public func toAttributedStringByPercentX(_ subBuilder:(_ rawFormatStr: String, _ isPercentStr: Bool)->NSAttributedString) -> NSAttributedString {
        let splits = self.splitFullByPercentX()
        let result = NSMutableAttributedString()
        var rawPercents = splits.1
        for rawFormat in splits.0 {
            let isPercentStr = rawPercents.contains(rawFormat)
            if isPercentStr { rawPercents.removeFirst() }
            result.append(subBuilder(rawFormat, isPercentStr))
        }
        return result
    }
    
    public func startsWith(_ string: String) -> Bool {        
        guard let range = range(of: string, options:[.anchored, .caseInsensitive]) else {
            return false
        }
        
        return range.lowerBound == startIndex
    }
}


extension String
{
    
    
    /** 将字符串里面的数字用特殊颜色标记。 */
    static public func highlightNumCountInString(_ totalStr : String,font:CGFloat,highlightColor:UIColor,textColor:UIColor) -> NSMutableAttributedString {
        
        let str = totalStr as NSString
        let attributedStr = NSMutableAttributedString(string: totalStr)
        attributedStr.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: font), range: NSMakeRange(0, totalStr.length))
        var tempChar : String?
        for i in 0..<totalStr.length {
            tempChar = str.substring(with: NSMakeRange(i, 1))
            if Int(tempChar!) != nil || tempChar == CommonDefine.kCurrencySymbol {
                attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: highlightColor, range: NSMakeRange(i,1))
            }else{
                attributedStr.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSMakeRange(i,1))
            }
        }
        return attributedStr
    }
}
